package com.example.sharesinfo.fragment.trade;


import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.sharesinfo.R;
import com.example.sharesinfo.adapter.CommonAdapter;
import com.example.sharesinfo.adapter.CommonViewHolder;
import com.example.sharesinfo.bean.TradeHistoryBean;
import com.example.sharesinfo.entity.Constants;
import com.example.sharesinfo.model.PositionModel;
import com.example.sharesinfo.model.TradeHistoryModel;
import com.example.sharesinfo.ui.SharesInfoActivity;
import com.example.sharesinfo.utils.CommonUtils;
import com.example.sharesinfo.utils.OkHttpUtils;
import com.example.sharesinfo.utils.SpUtils;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class TradingHistoryFragment extends Fragment {
    private TradingHistoryFragment fa;
    private static final String LOGTAG = "TradingHistoryFragment:";
    private static final int QUERYDATASUCCESS = 1001;
    private static final int QUERYDATAEMPTY = 1002;
    private RecyclerView mHistoryView;
    private View item_empty_view;
    private CommonAdapter<TradeHistoryModel> mHistoryAdapter;
    private List<TradeHistoryModel> mList = new ArrayList<>();

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case QUERYDATASUCCESS:
                    if (mList.size() > 0) {
                        mList.clear();
                    }

                    TradeHistoryBean result = (TradeHistoryBean) msg.obj;
                    if (result.getData().size() > 0) {
                        item_empty_view.setVisibility(View.GONE);
                        mList.addAll(result.getData());
                        mHistoryAdapter.notifyDataSetChanged();
                    } else {
                        item_empty_view.setVisibility(View.VISIBLE);
                    }

                    break;
                case QUERYDATAEMPTY:
                    break;
                case 404:
                    break;
            }
            return false;
        }
    });

    public TradingHistoryFragment getFragment() {
        if (fa == null) {
            fa = new TradingHistoryFragment();
        }
        return fa;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_trading_history, null);
        initView(view);
        queryData();
        return view;
    }

    private void initView(View view) {
        item_empty_view = view.findViewById(R.id.item_empty_view);
        mHistoryView = view.findViewById(R.id.mHistoryView);
        mHistoryView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mHistoryView.addItemDecoration(new DividerItemDecoration(getActivity(),
                DividerItemDecoration.VERTICAL));
        mHistoryAdapter = new CommonAdapter<>(mList, new CommonAdapter.OnBindDataListener<TradeHistoryModel>() {
            @Override
            public void onBindViewHolder(final TradeHistoryModel model, CommonViewHolder viewHolder, int type, int position) {
                viewHolder.setText(R.id.tv_stock_name, model.getStockName());
                viewHolder.setText(R.id.tv_stock_code, model.getStockCode());
                viewHolder.setText(R.id.tv_stock_amount, String.valueOf(model.getTransactionAmount()));
                viewHolder.setText(R.id.tv_stock_price, String.valueOf(model.getTransactionPrice()));
                viewHolder.setText(R.id.tv_stock_value, String.valueOf(model.getTransactionValue()));
                viewHolder.setText(R.id.tv_stock_type, model.getTransactionType());
                if (model.getTransactionType().equals("买入")) {
                    ((TextView) viewHolder.getView(R.id.tv_stock_type)).setTextColor(0xFF169619);
                } else {
                    ((TextView) viewHolder.getView(R.id.tv_stock_type)).setTextColor(0xFFED382B);
                }
                viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SharesInfoActivity.startActivity(getContext(), model.getStockCode());
                    }
                });
            }

            @Override
            public int getLayoutId(int type) {
                return R.layout.trading_history_list_item;
            }
        });
        mHistoryView.setAdapter(mHistoryAdapter);
    }

    /**
     * 查询历史交易
     */

    private void queryData() {
        String url = "http://119.23.221.142/api/account/GetTradeHistory?UserId="
                + SpUtils.getInstance().getString(Constants.SP_USER_ID, "");
        OkHttpUtils.getInstance().Get(url, new OkHttpUtils.okHttpListener() {
            Message message = mHandler.obtainMessage();

            @Override
            public void OnSuccess(String s, int code) throws JSONException {
                JSONObject object = new JSONObject(s);
                if (object.getString("code").equals("200")) {
                    TradeHistoryBean bean = new Gson().fromJson(s, TradeHistoryBean.class);
                    message.what = QUERYDATASUCCESS;
                    message.obj = bean;
                    mHandler.sendMessage(message);
                } else {
                    message.what = QUERYDATAEMPTY;
                    message.obj = object.getString("message");
                    mHandler.sendMessage(message);
                }
            }

            @Override
            public void OnFailed(String s) {
                message.what = 404;
                message.obj = s;
                mHandler.sendMessage(message);
            }
        });
    }


}
